declare module 'lodash-es';

<script setup lang="ts">
import { createVNode, onMounted, ref, watch } from "vue";
import {
  orderInfoDelete,
  orderInfoGetOne,
  orderInfoQueryPage,
  orderInfoSave,
  orderInfoUpdate,
  quickAddReq,
  quickDelete,
} from "@/api/orderInfo";
import { RangeValue } from "ant-design-vue/es/vc-picker/interface";
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import dayjs, { Dayjs } from "dayjs";
import { exportOrderInfoData, startRequest, stop } from "@/api/main";
import { debounce } from "lodash-es";
import { getMark, getMarkDate } from "@/api/ezConfig";

onMounted(async () => {
  search();
  searchEzConfig();
});
const ezMark = ref("");
const searchEzConfig = async () => {
  const res = await getMark();
  ezMark.value = res.data;
};
watch(ezMark, (newVal, oldVal) => {
  if (newVal === "0") {
    checked.value = false;
  } else {
    checked.value = true;
  }
});
const performSearch = () => {
  loading.value = true;
  orderInfoQueryPage(queryInfo.value).then((res) => {
    data.value = res.data.records;
    pagination.value = {
      total: res.data.total,
      current: res.data.current,
      pageSize: res.data.size,
    };
    loading.value = false;
  });
};

const search = debounce(performSearch, 300);

const handleTableChange = (pag: { pageSize: number; current: number }) => {
  queryInfo.value.page = pag.current;
  queryInfo.value.pageSize = pag.pageSize;
  search();
};

const loading = ref(true);
const pagination = ref({
  total: undefined,
  current: undefined,
  pageSize: undefined,
});
const queryInfo = ref({
  code: "",
  endTime: "",
  material: "",
  orderCode: "",
  page: 0,
  pageSize: 10,
  startTime: "",
});
const columns = [
  { title: "Code", dataIndex: "code", key: "code" },
  { title: "订单号", dataIndex: "orderCode", key: "orderCode" },
  { title: "材料", dataIndex: "material", key: "material" },
  { title: "材料尺寸", dataIndex: "materialSize", key: "materialSize" },
  { title: "数量", dataIndex: "sideNumber", key: "sideNumber" },
  {
    title: "单/双面",
    dataIndex: "printSide",
    key: "printSide",
  },
  {
    title: "时间",
    dataIndex: "printTime",
    key: "printTime",
  },
  { title: "操作", dataIndex: "operation", key: "operation" },
];

const data = ref([]);
//addAndUpdate
const orderInfo = ref({
  code: "",
  orderCode: "",
  material: "",
  materialSize: "",
  sideNumber: "",
  printSide: "",
});
// form表单
const searchFormInfo = ref({
  code: "",
  orderCode: "",
  startTime: "",
  endTime: "",
});
const time = ref<RangeValue>();
// 如果 time 的值是从后端返回的，需要进行时区转换
watch(time, (newVal, oldVal) => {
  if (newVal !== null) {
    const start = dayjs(newVal[0]);
    const end = dayjs(newVal[1]);
    //将时间转为 dayjs 对象并设置为 UTC+8 时区
    searchFormInfo.value.startTime = start.format();
    searchFormInfo.value.endTime = end.format();
  } else {
    searchFormInfo.value.startTime = "";
    searchFormInfo.value.endTime = "";
  }
});
const reset = () => {
  searchFormInfo.value = {
    code: "",
    orderCode: "",
    startTime: "",
    endTime: "",
  };
  queryInfo.value = {
    code: "",
    endTime: "",
    material: "",
    orderCode: "",
    page: 0,
    pageSize: 10,
    startTime: "",
  };
  time.value = null;
  search();
};
const addOpen = ref(false);
const deleteOpen = ref(false);
const deleteOrderInfo = async () => {
  const res = await quickDelete(deleteCode.value);
  if (res) {
    message.success("删除成功");
    search();
    deleteCode.value = "";
  }
};
// 添加数据
const activeKey = ref("1");
const addModal = () => {
  addOpen.value = true;
  activeKey.value = "1";
  orderInfo.value = {
    code: "",
    orderCode: "",
    material: "",
    materialSize: "",
    sideNumber: "",
    printSide: "0",
  };
};
const addOrderInfo = async () => {
  if (activeKey.value == "1") {
    const res = await quickAddReq(addCode.value);
    if (res) {
      message.success("添加成功");
      addCode.value = "";
      search();
    }
  } else {
    const res = await orderInfoSave(orderInfo.value);
    if (res) {
      message.success("添加成功");
      addOpen.value = false;
      search();
    }
  }
};
//自动添加
const addCode = ref("");
//手动添加
//模态框 删除-->
const deleteCode = ref("");
// 搜索-->
const onSubmit = () => {
  queryInfo.value.code = searchFormInfo.value.code;
  queryInfo.value.orderCode = searchFormInfo.value.orderCode;
  queryInfo.value.startTime = searchFormInfo.value.startTime;
  queryInfo.value.endTime = searchFormInfo.value.endTime;
  search();
};
// 删除Modal
const showDeleteConfirm = (id: number) => {
  Modal.confirm({
    title: "确认删除数据？",
    icon: createVNode(ExclamationCircleOutlined),
    okText: "确认",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      const res = await orderInfoDelete({
        id: id,
      });
      if (res) {
        message.success("删除成功");
        search();
      }
    },
  });
};
//handleEdit 编辑
const editOpen = ref(false);
const handleEdit = async (record: any) => {
  editOpen.value = true;
  const res = await orderInfoGetOne(record);
  orderInfo.value = res.data;
  orderInfo.value.printSide = orderInfo.value.printSide.toString();
};
const editOrderInfo = async () => {
  const res = await orderInfoUpdate(orderInfo.value);
  if (res) {
    message.success("修改成功");
    editOpen.value = false;
    search();
  }
};
//导出为Excel
const exportExcelOpen = ref(false);
const exportExcelName = ref("default_name");
const exportExcel = async () => {
  exportExcelOpen.value = true;
};
const doExportExcel = async () => {
  const res = await exportOrderInfoData({
    startTime: searchFormInfo.value.startTime,
    endTime: searchFormInfo.value.endTime,
  }); // 获取二进制响应数据
  if (res instanceof Blob) {
    const blob = new Blob([res], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = exportExcelName.value;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  }
  exportExcelOpen.value = false;
};
//开始按钮
const checked = ref(false);
const beginOpen = ref(false);
const handleChange = (value: string) => {
  mark.value = value;
};
const onChangeBegin = async (check: boolean) => {
  if (check) {
    beginOpen.value = true;
  } else {
    const resMark = await getMark();
    const resStop = await stop();
    const dateMarkRes = await getMarkDate();
    const shift = getShift(resMark.data);
    if (resStop && dateMarkRes && resMark) {
      blobExportExcel(resStop, dateMarkRes.data + "-" + shift);
    } else {
      checked.value = false;
    }
  }
};
const getShift = (markRes: number) => {
  if (markRes == 1) {
    return "白";
  }
  if (markRes == 2) {
    return "中";
  }
  if (markRes == 3) {
    return "夜";
  }
  return "";
};
const markDate = ref<Dayjs>();
const mark = ref("");
const beginOK = async () => {
  const res = await startRequest({
    orderInfoMark: mark.value,
    orderInfoDate: dayjs(markDate.value).format("YYYY-MM-DD"),
  });
  checked.value = !!res;
  beginOpen.value = false;
};
const beginCancel = () => {
  beginOpen.value = false;
  checked.value = false;
};

function blobExportExcel(res: any, fileName: string) {
  if (res instanceof Blob) {
    const blob = new Blob([res], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = fileName + ".xlsx";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  }
}
</script>

<template>
  <div>
    <a-modal
      v-model:open="deleteOpen"
      ok-type="danger"
      title="快捷删除"
      @ok="deleteOrderInfo"
    >
      <a-input
        v-model:value="deleteCode"
        placeholder="输入code删除"
        @keydown.enter="deleteOrderInfo"
      />
    </a-modal>
  </div>
  <!--  添加数据-->
  <div>
    <a-modal v-model:open="addOpen" title="添加" @ok="addOrderInfo">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="自动添加">
          <a-input
            v-model:value="addCode"
            placeholder="输入code添加"
            @keydown.enter="addOrderInfo"
          />
        </a-tab-pane>
        <a-tab-pane key="3" tab="手动添加">
          <a-form-item label="Code">
            <a-input v-model:value="orderInfo.code" />
          </a-form-item>
          <a-form-item label="订单号">
            <a-input v-model:value="orderInfo.orderCode" />
          </a-form-item>
          <a-form-item label="材料">
            <a-input v-model:value="orderInfo.material" />
          </a-form-item>
          <a-form-item label="尺寸">
            <a-input v-model:value="orderInfo.materialSize" />
          </a-form-item>
          <a-form-item label="数量">
            <a-input v-model:value="orderInfo.sideNumber" />
          </a-form-item>
          <a-form-item label="单/双面">
            <a-select
              ref="select"
              v-model:value="orderInfo.printSide"
              style="width: 120px"
            >
              <a-select-option value="0">单面</a-select-option>
              <a-select-option value="1">双面</a-select-option>
            </a-select>
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
  <!--  form表单-->
  <a-form :model="searchFormInfo" layout="inline">
    <a-form-item label="Code">
      <a-input v-model:value="searchFormInfo.code" />
    </a-form-item>
    <a-form-item label="订单号">
      <a-input v-model:value="searchFormInfo.orderCode" />
    </a-form-item>
    <a-form-item label="时间">
      <a-space direction="vertical" :size="12">
        <a-range-picker v-model:value="time" show-time />
      </a-space>
    </a-form-item>
    <a-button type="default" @click="reset">重置</a-button>
    <a-divider type="vertical" />
    <a-button type="primary" @click="onSubmit">搜索</a-button>
    <div style="margin-left: auto">
      <a-button type="link" @click="exportExcel">导出为excel</a-button>
      <a-modal
        v-model:open="exportExcelOpen"
        title="导出文件名"
        @ok="doExportExcel"
      >
        <a-input v-model:value="exportExcelName" />
      </a-modal>
      <a-divider type="vertical" />

      <a-button type="primary" @click="addModal">添加</a-button>
      <a-divider type="vertical" />
      <a-button danger @click="() => (deleteOpen = true)">快捷删除</a-button>
      <a-divider type="vertical" />

      <a-switch
        v-model:checked="checked"
        checked-children="开"
        un-checked-children="关"
        @change="onChangeBegin"
      />
    </div>
  </a-form>

  <!--  表格-->
  <a-table
    :columns="columns"
    :data-source="data"
    :pagination="pagination"
    :loading="loading"
    @change="handleTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'printSide'">
        <span v-if="record.printSide === 0">单面</span>
        <span v-if="record.printSide === 1">双面</span>
      </template>
      <template v-if="column.dataIndex === 'operation'">
        <a-button default @click="() => handleEdit(record.id)">编辑</a-button>
        <a-divider type="vertical" />
        <a-button danger @click="showDeleteConfirm(record.id)">删除</a-button>
      </template>
    </template>
  </a-table>
  <a-modal v-model:open="editOpen" title="编辑" @ok="editOrderInfo">
    <a-form-item label="Code">
      <a-input v-model:value="orderInfo.code" />
    </a-form-item>
    <a-form-item label="订单号">
      <a-input v-model:value="orderInfo.orderCode" />
    </a-form-item>
    <a-form-item label="材料">
      <a-input v-model:value="orderInfo.material" />
    </a-form-item>
    <a-form-item label="尺寸">
      <a-input v-model:value="orderInfo.materialSize" />
    </a-form-item>
    <a-form-item label="数量">
      <a-input v-model:value="orderInfo.sideNumber" />
    </a-form-item>
    <a-form-item label="单/双面">
      <a-select
        ref="select"
        v-model:value="orderInfo.printSide"
        style="width: 120px"
      >
        <a-select-option value="0">单面</a-select-option>
        <a-select-option value="1">双面</a-select-option>
      </a-select>
    </a-form-item>
  </a-modal>
  <!--  开始模态框-->
  <a-modal
    v-model:open="beginOpen"
    title="选择班次"
    @ok="beginOK"
    @cancel="beginCancel"
  >
    <div style="display: flex; align-items: center">
      <a-date-picker v-model:value="markDate" style="margin-right: 16px" />
      <a-select ref="select" style="width: 100px" @change="handleChange">
        <a-select-option value="1">白</a-select-option>
        <a-select-option value="2">中</a-select-option>
        <a-select-option value="3">夜</a-select-option>
      </a-select>
    </div>
  </a-modal>
</template>

<style scoped></style>
